const bfPwdPrefix = "performancing:";

var gTempPost = false;
var gTempTitleString = '';
var gTempBody = '';

function performancingUtil() {
    this.prefsService = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService);
    this.prefs = this.prefsService.getBranch("performancing.");
    this.currentURL = null;
    this.currentPass = null;
    this.charType = null;
	this.currentBlogName = null;
}

performancingUtil.prototype.onPFFWindowClose = function(){
	performancingEditor.saveState();
	SCRIBEFIRE_DB.closeDB(true, true);
}

performancingUtil.prototype.setupLivePreview = function () {
	performancingEditor.getCurrentEditorDocument().getElementById("performancing-publish-deck").selectedIndex = 3;
	gPerformancingUtil.publishTemporaryPost();
};

performancingUtil.prototype.publishTemporaryPost = function () {
	function randomString(string_length) {
		var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
		var randomstring = '';
		for (var i=0; i<string_length; i++) {
			var rnum = Math.floor(Math.random() * chars.length);
			randomstring += chars.substring(rnum,rnum+1);
		}
		return randomstring;
	}
	
	gTempTitleString = "SCRIBEFIRE"+randomString(10)+"SCRIBEFIRE";
	gTempBody = "SCRIBEFIRE"+randomString(8)+"SCRIBEFIRE";
	
	gTempPost = true;
	gPerformancingUtil.publish({title:gTempTitleString, content:gTempBody});
};

performancingUtil.prototype.grabBlogCode = function (postId) {
	var req = new XMLHttpRequest();
	req.open("GET", SCRIBEFIRE_BLOG.url, true);
	
	req.onreadystatechange = function () {
		if (req.readyState == 4) {
			var titleRE = new RegExp(gTempTitleString, "ig");
			var bodyRE = new RegExp(gTempBody, "ig");
			
			var template = req.responseText.replace(titleRE, "%%SF_TITLE%%").replace(bodyRE, "%%SF_BODY%%");
			template = template.replace("</head>", "<base href=\""+SCRIBEFIRE_BLOG.url+"\"></head>");
			
			SCRIBEFIRE_DB.saveBlogTemplate(SCRIBEFIRE_BLOG.guid, template, true);
			
			gPerformancingUtil.deleteTemporaryPost(postId);
		}
	};
	
	req.send(null);
};

performancingUtil.prototype.deleteTemporaryPost = function (postId) {
	gPerformancingUtil.deleteHistoryItem(postId);
};

performancingUtil.prototype.init = function(){
	try {
		SCRIBEFIRE_DB.load();
		gPerformancingUtil.convertBlogXMLToDB();
		performancingUI.init();
		SCRIBEFIRE_NOTES.init();
		SCRIBEFIRE_HISTORY.load();
		
		var pane = this.prefs.getCharPref("pendingPane");

		if (pane != '') {
			this.prefs.setCharPref("pendingPane", "");
			performancingUI.onLeftSidebarTabSelect(pane);
		}
	}catch(e){
		alert("ScribeFire startup error: " + e);
	}
}

performancingUtil.prototype.printLog = function(theServiceMessage){
    SFLOG(theServiceMessage);
}

performancingUtil.prototype.getXHTML = function (text) {
    //Fix closing tags on single elements
    text = text.replace(/<(br|hr|img)([^>]*)([^\/])>/gi, "<$1$2$3 />");
    //Remove extra space in case it was formatted as <br > - not a big deal
    text = text.replace(/<(br|hr|img)([^>]*)  \/>/gi, "<$1$2 />");
    //Add space if it is <br style=""/> at this point
    text = text.replace(/<(br|hr|img)([^>]*)"\/>/gi, "<$1$2\" />");
    //Make sure br is closed
    text = text.replace(/<br>/gi, "<br />");
	text = text.replace(/<hr>/gi, "<hr />");
	text = text.replace(/\s*<\/param>/gi, "");
	text = text.replace(/(<param[^>]+>)/gi, "$1 </param>");
	text = text.replace(/\s*<\/embed>/gi, "");
	text = text.replace(/(<embed[^>]+>)/gi, "$1 </embed>");
	text = text.replace(/\/>\s*<\/embed>/gi, "> </embed>");
	text = text.replace(/\/>\s*<\/param>/gi, "> </param>");
	
	// Add a <div class="youtube-video" wrapper to any embed or object tags
	text = text.replace(/<div[^>]+><object/gi, "<object");
	text = text.replace(/<\/object><\/div>/gi, "</object>");
	
	text = text.replace(/<object/gi, '<div class="youtube-video"><object');
	text = text.replace(/<\/object>/gi, '</object></div>');
	
    return text;
}

/*
<blog>
    <blogname>{theBlogName}</blogname>
    <blogtype>{theBlogType}</blogtype>
    <appkey>{theAppKey}</appkey>
    <username>{theUserName}</username>
    <apiurl>{theAPIURL}</apiurl>
    <GUID>{theGUID}</GUID>
    <url>{theURL}</url>
    <blogid>{theBlogID}</blogid>
</blog>
*/

/*'*/


performancingUtil.prototype.convertBlogXMLToDB = function () {
	var file = gPerformancingUtil.getFilePath("performancing-bloglist.xml");
	var f2 = PerFormancingFileIO.open(file.path);

	if (f2.exists()) {
		var db = SCRIBEFIRE_DB.getDB();
		
		var theXMLString = PerFormancingFileIO.read(file, "UTF-8");
		var xmlObject = new XML(theXMLString);
		
		var numberOfBlogs = xmlObject..blog.length();
		
		if (numberOfBlogs > 0) {
			for (var x = 0; x < numberOfBlogs; x++) {
				var blog = xmlObject..blog[x];
				var insert = db.createStatement("INSERT INTO "+SCRIBEFIRE_DB.blogsTable+" (name, type, api, key, username, guid, url, blogId, useBoolean) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)");
				insert.bindUTF8StringParameter(0, blog.blogname.toString());
				insert.bindUTF8StringParameter(1, blog.blogtype.toString());
				insert.bindUTF8StringParameter(2, blog.apiurl.toString());
				insert.bindUTF8StringParameter(3, blog.appkey.toString());
				insert.bindUTF8StringParameter(4, blog.username.toString());
				insert.bindUTF8StringParameter(5, blog.GUID.toString());
				insert.bindUTF8StringParameter(6, blog.url.toString());
				insert.bindUTF8StringParameter(7, blog.blogid.toString());
				insert.bindUTF8StringParameter(8, blog.useboolean.toString());
				insert.execute();
			}
		}
		
		SCRIBEFIRE_DB.closeDB(db);
		
		// Move the file out of the way.
		var file = gPerformancingUtil.getFilePath("performancing-bloglist-old.xml", true);
		PerFormancingFileIO.write(file, theXMLString, "w", "UTF-8");
		
		// Delete the old file and filename.
		var oldFile = gPerformancingUtil.getFilePath("performancing-bloglist.xml");
		PerFormancingFileIO.unlink(oldFile);
	}
}

performancingUtil.prototype.loadBlogs = function () {
	var ourDeck = document.getElementById('performancing-account-deck');
	var db = SCRIBEFIRE_DB.getDB();
	
	var select = db.createStatement("SELECT name, url, guid FROM "+SCRIBEFIRE_DB.blogsTable);
	
	ourDeck.setAttribute('selectedIndex','1');
	gPerformancingUtil.emptyElement('blog-group-rows');
	
	var numBlogs = 0;
	
	try {
		while (select.executeStep()) {
			numBlogs++;
			ourDeck.setAttribute('selectedIndex','0');
			gPerformancingUtil.addBlogToGroup(select.getUTF8String(0), select.getUTF8String(1), select.getUTF8String(2));
		}
	} catch (e) {
		SFLOG(e);
	} finally {
		select.reset();
		
	    var blogGUID = SCRIBEFIRE_BLOG.findGUID();
		
		SCRIBEFIRE_BLOG.guid = blogGUID;
		performancingUI.showCurrentBlog();
	}
}

performancingUtil.prototype.getFilePath = function (filename, inMainProfileDir) {
	var file = PerFormancingDirIO.get("ProfD");
	
	if (!inMainProfileDir) {
		file.append("extensions");
	}
	
	file.append(filename);

	return file;
}

performancingUtil.prototype.delete = function () {
	switch (performancingEditor.getEntryType()) {
		case 'post':
			this.deleteHistoryItem();
		break;
		case 'page':
			this.deletePage();
		break;
		case 'note':
		default:
			if (performancingEditor.getEntryId()) {
				SCRIBEFIRE_NOTES.deleteNoteEntry();
			}
			else {
				performancingEditor.closeTab();
			}
		break;
	}
}

performancingUtil.prototype.editBlog = function () {
	var blogGroup = document.getElementById("blog-group");
	
	if (blogGroup.selectedItem) {
		var theGUID = blogGroup.selectedItem.getAttribute('blogGUID');
	}
	else {
		alert(performancingUI.getLocaleString('mustselectblog'));
	}
	
	window.openDialog("chrome://scribefire/content/editBlog.xul", "performancing-edit-blog", "chrome,centerscreen", theGUID);
};

performancingUtil.prototype.editBlogLoad = function (guid) {
	SCRIBEFIRE_BLOG.guid = guid;
	
	var password = this.goGetPassword(SCRIBEFIRE_BLOG.username, SCRIBEFIRE_BLOG.url);
	
	document.getElementById("blog-title").value = SCRIBEFIRE_BLOG.name;
	document.getElementById("blog-url").value = SCRIBEFIRE_BLOG.url;
	document.getElementById("blog-username").value = SCRIBEFIRE_BLOG.username;
	document.getElementById("blog-password").value = password;
	document.getElementById("blog-api-url").value = SCRIBEFIRE_BLOG.api;
	document.getElementById("blog-key").value = SCRIBEFIRE_BLOG.key;
	document.getElementById("blog-boolean").checked = (SCRIBEFIRE_BLOG.useBoolean == 'true');
	
    var thePassword = gPerformancingUtil.usermanagment.getPassword(SCRIBEFIRE_BLOG.ftp_username, "-ftp-" + SCRIBEFIRE_BLOG.ftp_host);
    
	document.getElementById("ftp-username").value = SCRIBEFIRE_BLOG.ftp_username;
    document.getElementById("ftp-host").value = SCRIBEFIRE_BLOG.ftp_host;
    document.getElementById("ftp-password").value = thePassword;
    document.getElementById("ftp-path").value = SCRIBEFIRE_BLOG.ftp_path;
    document.getElementById("ftp-url-to-path").value = SCRIBEFIRE_BLOG.ftp_url_to_path;
        
    var theProtocol = SCRIBEFIRE_BLOG.ftp_protocol;
    
    if (theProtocol == "ftp"){
        document.getElementById("ftp-protocol").selectedIndex = 0;
    }
    else if(theProtocol == "http"){
        document.getElementById("ftp-protocol").selectedIndex = 1;
    }
    else{
        document.getElementById("ftp-protocol").selectedIndex = 2;
    }
};


performancingUtil.prototype.saveBlog = function (guid) {
	SCRIBEFIRE_BLOG.guid = guid;
	
	SCRIBEFIRE_BLOG.name = document.getElementById("blog-title").value;
	SCRIBEFIRE_BLOG.url = document.getElementById("blog-url").value;
	SCRIBEFIRE_BLOG.username = document.getElementById("blog-username").value;
	SCRIBEFIRE_BLOG.api = document.getElementById("blog-api-url").value;
	SCRIBEFIRE_BLOG.key = document.getElementById("blog-key").value;
	SCRIBEFIRE_BLOG.useBoolean = document.getElementById("blog-boolean").checked.toString();
	
	gPerformancingUtil.getOpener(window).gPerformancingUtil.usermanagment.storeLoginDetails(
		document.getElementById("blog-username").value,
		document.getElementById("blog-password").value,
		document.getElementById("blog-url").value);
	
	gPerformancingUtil.getOpener(window).SCRIBEFIRE_BLOG.password = document.getElementById("blog-password").value;
	gPerformancingUtil.getOpener(window).gPerformancingUtil.currentPass = document.getElementById("blog-password").value;
	
	gPerformancingUtil.getOpener(window).performancingUI.reLoadBlogs();
	
	SCRIBEFIRE_BLOG.ftp_username = document.getElementById("ftp-username").value;
	SCRIBEFIRE_BLOG.ftp_host = document.getElementById("ftp-host").value;
	SCRIBEFIRE_BLOG.ftp_protocol = document.getElementById("ftp-protocol").selectedItem.value;
    SCRIBEFIRE_BLOG.ftp_path = document.getElementById("ftp-path").value;
    SCRIBEFIRE_BLOG.ftp_url_to_path = document.getElementById("ftp-url-to-path").value;
    
	var ftp_password = document.getElementById("ftp-password").value;
	
	if (SCRIBEFIRE_BLOG.ftp_username && ftp_password) {
	    var addedUser = gPerformancingUtil.usermanagment.storeLoginDetails(SCRIBEFIRE_BLOG.ftp_username, ftp_password, "-ftp-" + SCRIBEFIRE_BLOG.ftp_host);
    }
	
	return true;
}

performancingUtil.prototype.getOpener = function (win) {
	if (win.opener.wrappedJSObject) {
		return win.opener.wrappedJSObject;
	}
	
	return win.opener;
};

performancingUtil.prototype.addBlogToGroup = function (name, url, guid) {
	var group = document.getElementById("blog-group-rows");
	
	var row = document.createElement("row");
	var r = document.createElement("radio");
	r.setAttribute("id","blog-" + group.getElementsByTagName("radio").length);
	r.setAttribute("blogGUID",guid);
	r.setAttribute("tooltiptext", url);
	r.blogName = name;
	r.setAttribute("onclick","performancingUI.onBlogSelect(this);");

	var link = document.createElement("label");
	link.setAttribute("value",name);
	link.setAttribute("tooltiptext", url);
	link.setAttribute("onclick","performancingUI.openInTab('" + url + "');");
	link.setAttribute("class","link");

	row.appendChild(r);
	row.appendChild(link);
	group.appendChild(row);
};

performancingUtil.prototype.addItemToList = function(dataArray, number, listIDname, theGUID, theURL, onItemClick, aDate, aPostId, theClass, theLink, isDraft, isScheduled){
    var list = document.getElementById(listIDname);
    var item = document.createElement('listitem');
    item.setAttribute('id', 'blog-' + number);
    item.setAttribute('blogGUID', theGUID);
    item.setAttribute('tooltiptext', theURL);
    item.setAttribute('date', aDate);
    item.setAttribute('postid', aPostId);
    item.setAttribute('onclick', onItemClick);
    item.setAttribute('class', theClass);
	item.setAttribute("url", theLink);
    
	if (isScheduled) {
		item.style.color = '#00f';
	}
	else if (isDraft) {
		item.style.color = '#f00';
	}

    for(var i=0; i < dataArray.length; i++){
        var itemCell = document.createElement('listcell');
        itemCell.setAttribute('label', dataArray[i]);
        itemCell.setAttribute('crop', 'right');
        itemCell.setAttribute('class', theClass + '2');
        item.appendChild(itemCell);
    }
    //Append the elements
    list.appendChild(item);
    //sizeToContent();
}

performancingUtil.prototype.addItemToCheckList = function(dataArray, number, checkListIDname, theGUID, aCategory, onItemClick, AType, isChecked){
    if(isChecked != true){
        isChecked = false;
    }
    
    var checkList = document.getElementById(checkListIDname);
    if(AType != 'label'){
        var checkbox = document.createElement('checkbox');
        checkbox.setAttribute('id', 'blog-' + number);
        checkbox.setAttribute('cat', aCategory);
        checkbox.setAttribute('checked', isChecked);
		checkbox.setAttribute("oncommand", "performancingEditor.updateCategories();");
        for(i=0; i < dataArray.length; i++){
            checkbox.setAttribute('label', dataArray[i]);
            checkList.appendChild(checkbox);
        }
    }else{
        var label = document.createElement('label');
        label.setAttribute('id', 'blog-' + number);
        label.setAttribute('value', dataArray[0]);
        checkList.appendChild(label);
    }
}

performancingUtil.prototype.emptyElement = function (groupID) {
	var group = document.getElementById(groupID);
	while (group.lastChild) group.removeChild(group.lastChild);
};

performancingUtil.prototype.clearListOut = function(listIDname){
    var list=document.getElementById(listIDname);
    while(list.getRowCount() > 0){
        list.removeItemAt( list.getRowCount() - 1);
    }
}

performancingUtil.prototype.clearCheckListOut = function(checkListIDname){
    var checkList = document.getElementById(checkListIDname);
    while( checkList.hasChildNodes() ){
        checkList.removeChild( checkList.firstChild );
    }
}

//gPerformancingUtil.convertFromUnicode(theOldText, encodingType); //"iso-8859-1"
performancingUtil.prototype.convertFromUnicode = function(aOldText, encodingType){
    var uniConverter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
    uniConverter.charset = encodingType; //"iso-8859-1"
    var theNewText = uniConverter.ConvertFromUnicode(aOldText);
    return theNewText;
}

performancingUtil.prototype.getCharType = function(){
    if(this.charType == null){
        try{
            this.charType = gPerformancingUtil.prefs.getCharPref("settings.defaults.encoding");
        }catch(e){
            this.charType = "UTF-8";
        }
    }
    return this.charType;
}

//We get the password, if it doesn't exist, we prompt user for the password.
performancingUtil.prototype.goGetPassword = function(aUserName, aURL){
    //If same as last call, we've cached the password.
    if(this.currentURL == aURL){
        return this.currentPass;
    }else{
        var thePassword = gPerformancingUtil.usermanagment.getPassword(aUserName, aURL);
        if(thePassword){
            this.currentURL = aURL;
            this.currentPass = thePassword;
            return thePassword;
        }else{
            var localeString = performancingUI.getLocaleString('pleaseenterpassword', [aURL]);
			var dialogTitle = performancingUI.getLocaleString('pleaseenterpasswordtitle');
			
			var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
                        	.getService(Components.interfaces.nsIPromptService);
			var password = { value : "" };
			var check = { value: false };
			var okorcancel = prompts.promptPassword(window, dialogTitle, localeString, password, null, check);
			
			if (okorcancel && password.value) {
				var aPassword = password.value;

	            var addedUser = gPerformancingUtil.usermanagment.storeLoginDetails(aUserName, aPassword, aURL);
	            this.currentURL = aURL;
	            this.currentPass = aPassword;
	            return aPassword;
			}
			else {
				return null;
			}
        }
    }
}

performancingUtil.prototype.usermanagment = {
	storeLoginDetails : function(myUserName, aPassword, aURL){
		// Get Password Manager (does not exist in Firefox 3)
		var CC_passwordManager = Components.classes["@mozilla.org/passwordmanager;1"];
		var CC_loginManager = Components.classes["@mozilla.org/login-manager;1"];

		if (CC_passwordManager != null) {
			// Password Manager exists so this is not Firefox 3 (could be Firefox 2, Netscape, SeaMonkey, etc).
			var newURL = bfPwdPrefix + aURL;

			if(myUserName){
				this._passwordManager = CC_passwordManager.createInstance();
				
				if (this._passwordManager) {
					this._passwordManager = this._passwordManager.QueryInterface(Components.interfaces.nsIPasswordManager);

					try{
						this._passwordManager.removeUser(newURL, myUserName);
					} catch (e) {
					}

					if (aPassword) {
						this._passwordManager.addUser(newURL, myUserName, aPassword);
						return true;
					}  
				} else {
					return false;
				}
			}

			return false;
		}
		else if (CC_loginManager!= null) {
			// Login Manager exists so this is Firefox 3
			var newURL = bfPwdPrefix + aURL;
			
			if (myUserName) {
				this._passwordManager = CC_loginManager.getService(Components.interfaces.nsILoginManager);
				
				var logins = this._passwordManager.findLogins({}, newURL, "chrome://scribefire", null);

				for (var j = 0; j < logins.length; j++) {
					this._passwordManager.removeLogin(logins[j]);
				}
				
				var nsLoginInfo = new Components.Constructor("@mozilla.org/login-manager/loginInfo;1", Components.interfaces.nsILoginInfo, "init");
				var loginInfo = new nsLoginInfo(newURL, 'chrome://scribefire', null, myUserName, aPassword, "", "");
				this._passwordManager.addLogin(loginInfo);

				return true;
			}

			return false;
		}
    },

	getPassword : function (aUserName, aURL) {
		// Get Password Manager (does not exist in Firefox 3)
		var CC_passwordManager = Components.classes["@mozilla.org/passwordmanager;1"];
		var CC_loginManager = Components.classes["@mozilla.org/login-manager;1"];

		if (CC_passwordManager != null) {
			// Password Manager exists so this is not Firefox 3 (could be Firefox 2, Netscape, SeaMonkey, etc).
			var newURL = bfPwdPrefix + aURL;
			this._passwordManager = CC_passwordManager.createInstance(Components.interfaces.nsIPasswordManagerInternal);
			this._host = { value : "" };
			this._user = { value : "" };
			this._password = { value : "" };

			try {
				this._passwordManager.findPasswordEntry(newURL, aUserName, "", this._host, this._user, this._password);
			} catch (e) {
				return false;
			}

			return this._password.value;
		}
		else if (CC_loginManager!= null) {
			// Login Manager exists so this is Firefox 3
			this._passwordManager = Components.classes["@mozilla.org/login-manager;1"].getService(Components.interfaces.nsILoginManager);
			var nsLoginInfo = new Components.Constructor("@mozilla.org/login-manager/loginInfo;1",
			                            Components.interfaces.nsILoginInfo, "init");
			var hostname = bfPwdPrefix + aURL;
			var formSubmitURL = null;
			var httprealm = null;
			var username = aUserName;

			// Get Login Manager 
			var myLoginManager = CC_loginManager.getService(Components.interfaces.nsILoginManager);
			var logins = myLoginManager.findLogins({}, hostname, formSubmitURL, null);

			for (var i = 0; i < logins.length; i++) {
				if (logins[i].username == username) {
					if (logins[i].formSubmitURL != 'chrome://scribefire') {
						var newLogin = new nsLoginInfo(hostname, 'chrome://scribefire', null, username, logins[i].password, "", "");
						this._passwordManager.modifyLogin(logins[i], newLogin);
					}
					
					return logins[i].password;
				}
			}

			var formSubmitURL = 'chrome://scribefire';
			
			// Get Login Manager 
			var logins = myLoginManager.findLogins({}, hostname, formSubmitURL, null);

			for (var i = 0; i < logins.length; i++) {
				if (logins[i].username == username) {
					return logins[i].password;
				}
			}

			return false;
		}
	}
}

performancingUtil.prototype.checkCategories = function(aCheck){
    //check or uncheck them.
    var checkList = document.getElementById('blog-sidebar-listing-categories');
    for(var k=0; k < checkList.childNodes.length; k++ ){
        checkList.childNodes[k].setAttribute("checked", aCheck);
    }
}

/*
    Set the categories for the post
*/
performancingUtil.prototype.setCategoriesSidebar = function(arrayCatList, aDoClear, DONOTCLEAR){
	performancingEditor.setCategories(arrayCatList);
	
	
	var theCheckList = document.getElementById('blog-sidebar-listing-categories');
	var doNotCheckClear = true;
	
    if( theCheckList.hasChildNodes() ){
		doNotCheckClear = (theCheckList.firstChild.nodeName == 'label') ;
    }
	else{
		doNotCheckClear = false;
    }
    
    if(aDoClear || doNotCheckClear) {
		if (!DONOTCLEAR) gPerformancingUtil.clearCheckListOut('blog-sidebar-listing-categories');
	}
    
    if(arrayCatList.length > 0){
        var checkList = document.getElementById('blog-sidebar-listing-categories');
        
        if(SCRIBEFIRE_BLOG.addCategories){
			// This API can create categories, so we'll create the checkboxes.
          	newCategories : for (var l = 0; l < arrayCatList.length; l++) {
				// Check if it already exists.
				for(var j = 0; j < checkList.childNodes.length; j++){
					if (checkList.childNodes[j].getAttribute('label') == arrayCatList[l]){
						checkList.childNodes[j].setAttribute("checked", true);
						continue newCategories;
					}
				}
				
                var theNewCatArray = arrayCatList[l].split(",");
                var theCategory1 = "";
                if(theNewCatArray.length > 1){
                    theCategory1 = theNewCatArray[1];
                }
                gPerformancingUtil.addItemToCheckList([theNewCatArray[0]], l, 'blog-sidebar-listing-categories', null, theCategory1, "", null, true );
            }
        }
		else{
			// This API can't actually create categories, so we'll just check them if they exist.
            gPerformancingUtil.checkCategories(false);
            for(x=0; x < arrayCatList.length; x++ ){
                for(i=0; i < checkList.childNodes.length; i++ ){
                    try{
                        if(checkList.childNodes[i].getAttribute('label') == arrayCatList[x]){
                            checkList.childNodes[i].setAttribute("checked", true);
                        }
                    }catch(e){
                        // Error getting categories from object
                        var localeString = performancingUI.getLocaleString('getcategorieserror', []);
                        alert(localeString);
                    }
                }
            }
        }
    }else{
        if(!doNotCheckClear && !DONOTCLEAR){
            if( performancingUI.hasCheckboxChildren('blog-sidebar-listing-categories') ) gPerformancingUtil.clearCheckListOut('blog-sidebar-listing-categories');
            var localeString = performancingUI.getLocaleString('nocategoriesavailable');
            var localeString2 = performancingUI.getLocaleString('notavailable');
            //No Categories Available
            gPerformancingUtil.addItemToCheckList([localeString], 0, 'blog-sidebar-listing-categories', null, localeString2, "", 'label' );
        }
    }
}

performancingUtil.prototype.setUpAPISpecificFunctions = function(aUID) {
	document.getElementById("tab-pages").setAttribute("disabled","true");
	document.getElementById("blog-sidebar-categories-addbtn").hidden = true;
	
	if (SCRIBEFIRE_BLOG.supportsPages) {
		// Not all MT APIs will support pages.  We should do a ping to make sure this is an
		// Up-to-date WP API
		
		// If the  getPageList API exists, then so do all the new pages APIs and a newCategory API
		
	    var myResponse = SCRIBEFIRE_BLOG.serviceObject.getPageList();
		
	    if (myResponse){
			performancing_xmlcall.sendCommand(SCRIBEFIRE_BLOG.api, myResponse, 'pagelistcall', "", aUID, performancing_xmlcall.processData);
			
			// For now, we'll use this as evidence that this blog also supports Wordpress's custom fields.
			// @todo Find a better way of determining whether custom fields are actually supported.
			SCRIBEFIRE_BLOG.supportsCustomFields = true;
		}
		else {
			SCRIBEFIRE_BLOG.supportsPages = false;
			SCRIBEFIRE_BLOG.supportsCustomFields = false;
		}
	}
	
	document.getElementById("blog-sidebar-categories-addbtn").hidden = !SCRIBEFIRE_BLOG.addCategories;
}

performancingUtil.prototype.namedEntitiesToNumericEntities = function (text) {
	var entities = {
		"nbsp" : "160",
		"iexcl" : "161",
		"cent" : "162",
		"pound" : "163",
		"curren" : "164",
		"yen" : "165",
		"brvbar" : "166",
		"sect" : "167",
		"uml" : "168",
		"copy" : "169",
		"ordf" : "170",
		"laquo" : "171",
		"not" : "172",
		"shy" : "173",
		"reg" : "174",
		"macr" : "175",
		"deg" : "176",
		"plusmn" : "177",
		"sup2" : "178",
		"sup3" : "179",
		"acute" : "180",
		"micro" : "181",
		"para" : "182",
		"middot" : "183",
		"cedil" : "184",
		"sup1" : "185",
		"ordm" : "186",
		"raquo" : "187",
		"frac14" : "188",
		"frac12" : "189",
		"frac34" : "190",
		"iquest" : "191",
		"agrave" : "192",
		"aacute" : "193",
		"acirc" : "194",
		"atilde" : "195",
		"auml" : "196",
		"aring" : "197",
		"aelig" : "198",
		"ccedil" : "199",
		"egrave" : "200",
		"eacute" : "201",
		"ecirc" : "202",
		"euml" : "203",
		"igrave" : "204",
		"iacute" : "205",
		"icirc" : "206",
		"iuml" : "207",
		"eth" : "208",
		"ntilde" : "209",
		"ograve" : "210",
		"oacute" : "211",
		"ocirc" : "212",
		"otilde" : "213",
		"ouml" : "214",
		"times" : "215",
		"oslash" : "216",
		"ugrave" : "217",
		"uacute" : "218",
		"ucirc" : "219",
		"uuml" : "220",
		"yacute" : "221",
		"thorn" : "222",
		"szlig" : "223",
		"agrave" : "224",
		"aacute" : "225",
		"acirc" : "226",
		"atilde" : "227",
		"auml" : "228",
		"aring" : "229",
		"aelig" : "230",
		"ccedil" : "231",
		"egrave" : "232",
		"eacute" : "233",
		"ecirc" : "234",
		"euml" : "235",
		"igrave" : "236",
		"iacute" : "237",
		"icirc" : "238",
		"iuml" : "239",
		"eth" : "240",
		"ntilde" : "241",
		"ograve" : "242",
		"oacute" : "243",
		"ocirc" : "244",
		"otilde" : "245",
		"ouml" : "246",
		"divide" : "247",
		"oslash" : "248",
		"ugrave" : "249",
		"uacute" : "250",
		"ucirc" : "251",
		"uuml" : "252",
		"yacute" : "253",
		"thorn" : "254",
		"yuml" : "255",
		"fnof" : "402",
		"alpha" : "913",
		"beta" : "914",
		"gamma" : "915",
		"delta" : "916",
		"epsilon" : "917",
		"zeta" : "918",
		"eta" : "919",
		"theta" : "920",
		"iota" : "921",
		"kappa" : "922",
		"lambda" : "923",
		"mu" : "924",
		"nu" : "925",
		"xi" : "926",
		"omicron" : "927",
		"pi" : "928",
		"rho" : "929",
		"sigma" : "931",
		"tau" : "932",
		"upsilon" : "933",
		"phi" : "934",
		"chi" : "935",
		"psi" : "936",
		"omega" : "937",
		"alpha" : "945",
		"beta" : "946",
		"gamma" : "947",
		"delta" : "948",
		"epsilon" : "949",
		"zeta" : "950",
		"eta" : "951",
		"theta" : "952",
		"iota" : "953",
		"kappa" : "954",
		"lambda" : "955",
		"mu" : "956",
		"nu" : "957",
		"xi" : "958",
		"omicron" : "959",
		"pi" : "960",
		"rho" : "961",
		"sigmaf" : "962",
		"sigma" : "963",
		"tau" : "964",
		"upsilon" : "965",
		"phi" : "966",
		"chi" : "967",
		"psi" : "968",
		"omega" : "969",
		"thetasym" : "977",
		"upsih" : "978",
		"piv" : "982",
		"bull" : "8226",
		"hellip" : "8230",
		"prime" : "8242",
		"prime" : "8243",
		"oline" : "8254",
		"frasl" : "8260",
		"weierp" : "8472",
		"image" : "8465",
		"real" : "8476",
		"trade" : "8482",
		"alefsym" : "8501",
		"larr" : "8592",
		"uarr" : "8593",
		"rarr" : "8594",
		"darr" : "8595",
		"harr" : "8596",
		"crarr" : "8629",
		"larr" : "8656",
		"uarr" : "8657",
		"rarr" : "8658",
		"darr" : "8659",
		"harr" : "8660",
		"forall" : "8704",
		"part" : "8706",
		"exist" : "8707",
		"empty" : "8709",
		"nabla" : "8711",
		"isin" : "8712",
		"notin" : "8713",
		"ni" : "8715",
		"prod" : "8719",
		"sum" : "8721",
		"minus" : "8722",
		"lowast" : "8727",
		"radic" : "8730",
		"prop" : "8733",
		"infin" : "8734",
		"ang" : "8736",
		"and" : "8743",
		"or" : "8744",
		"cap" : "8745",
		"cup" : "8746",
		"int" : "8747",
		"there4" : "8756",
		"sim" : "8764",
		"cong" : "8773",
		"asymp" : "8776",
		"ne" : "8800",
		"equiv" : "8801",
		"le" : "8804",
		"ge" : "8805",
		"sub" : "8834",
		"sup" : "8835",
		"nsub" : "8836",
		"sube" : "8838",
		"supe" : "8839",
		"oplus" : "8853",
		"otimes" : "8855",
		"perp" : "8869",
		"sdot" : "8901",
		"lceil" : "8968",
		"rceil" : "8969",
		"lfloor" : "8970",
		"rfloor" : "8971",
		"lang" : "9001",
		"rang" : "9002",
		"loz" : "9674",
		"spades" : "9824",
		"clubs" : "9827",
		"hearts" : "9829",
		"diams" : "9830",
		"quot" : "34",
		"amp" : "38",
		"lt" : "60",
		"gt" : "62",
		"oelig" : "338",
		"oelig" : "339",
		"scaron" : "352",
		"scaron" : "353",
		"yuml" : "376",
		"circ" : "710",
		"tilde" : "732",
		"ensp" : "8194",
		"emsp" : "8195",
		"thinsp" : "8201",
		"zwnj" : "8204",
		"zwj" : "8205",
		"lrm" : "8206",
		"rlm" : "8207",
		"ndash" : "8211",
		"mdash" : "8212",
		"lsquo" : "8216",
		"rsquo" : "8217",
		"sbquo" : "8218",
		"ldquo" : "8220",
		"rdquo" : "8221",
		"bdquo" : "8222",
		"dagger" : "8224",
		"dagger" : "8225",
		"permil" : "8240",
		"lsaquo" : "8249",
		"rsaquo" : "8250",
		"euro" : "8364"
	};
	
	for (var i in entities) {
		var re = new RegExp("&" + i + ";", "ig");
		
		text = text.replace(re, "&#" + entities[i] + ";");
	}
	
	return text;
};

performancingUtil.prototype.convertTextToHTML = function (htmlText, callback, callback2, args) {
	var Cc = Components.classes;
	var Ci = Components.interfaces;
	
	// Taken from http://mxr.mozilla.org/seamonkey/source/browser/components/microsummaries/src/nsMicrosummaryService.js#2116
	var windowMediator = Cc['@mozilla.org/appshell/window-mediator;1'].
							getService(Ci.nsIWindowMediator);
	var win = windowMediator.getMostRecentWindow("navigator:browser") || windowMediator.getMostRecentWindow(null);
	var doc = win.document;
	var rootElement = doc.documentElement;

	// Create an iframe, make it hidden, and secure it against untrusted content.
	var iframe = doc.createElement('iframe');
	iframe.setAttribute("collapsed", true);
	iframe.setAttribute("type", "content");
	
	// Insert the iframe into the window, creating the doc shell.
	rootElement.appendChild(iframe);

	// When we insert the iframe into the window, it immediately starts loading
	// about:blank, which we don't need and could even hurt us (for example
	// by triggering bugs like bug 344305), so cancel that load.
	var webNav = iframe.docShell.QueryInterface(Ci.nsIWebNavigation);
	webNav.stop(Ci.nsIWebNavigation.STOP_NETWORK);

	// Turn off JavaScript and auth dialogs for security and other things
	// to reduce network load.
	iframe.docShell.allowJavascript = false;
	iframe.docShell.allowAuth = false;
	iframe.docShell.allowPlugins = false;
	iframe.docShell.allowMetaRedirects = false;
	iframe.docShell.allowSubframes = false;
	iframe.docShell.allowImages = false;

	function handleParse(event) {
		iframe.removeEventListener("DOMContentLoaded", handleParse, false);
		
		if (iframe.contentWindow.wrappedJSObject) {
			var text = iframe.contentWindow.wrappedJSObject.document.body.innerHTML;
			var doc = iframe.contentWindow.wrappedJSObject.document;
		}
		else {
			var text = iframe.contentWindow.document.body.innerHTML;
			var doc = iframe.contentWindow.document;
		}
		
		callback(text, callback2, doc, args);
		
		rootElement.removeChild(iframe);
		iframe = null;
	}

	// Convert the HTML text into an input stream.
	var converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"].
	createInstance(Ci.nsIScriptableUnicodeConverter);
	converter.charset = "UTF-8";
	var stream = converter.convertToInputStream(htmlText);

	var uri = Components.classes['@mozilla.org/network/io-service;1'].getService(Components.interfaces.nsIIOService).newURI("http://www.example.com/", null, null);

	// Set up a channel to load the input stream.
	var channel = Cc["@mozilla.org/network/input-stream-channel;1"].
	createInstance(Ci.nsIInputStreamChannel);
	channel.setURI(uri);
	channel.contentStream = stream;

	// Load in the background so we don't trigger web progress listeners.
	var request = channel.QueryInterface(Ci.nsIRequest);
	request.loadFlags |= Ci.nsIRequest.LOAD_BACKGROUND;

	// Specify the content type since we're not loading content from a server,
	// so it won't get specified for us, and if we don't specify it ourselves,
	// then Firefox will prompt the user to download content of "unknown type".
	var baseChannel = channel.QueryInterface(Ci.nsIChannel);
	baseChannel.contentType = "text/html";

	// Load as UTF-8, which it'll always be, because XMLHttpRequest converts
	// the text (i.e. XMLHTTPRequest.responseText) from its original charset
	// to UTF-16, then the string input stream component converts it to UTF-8.
	baseChannel.contentCharset = "UTF-8";

	// Register the parse handler as a load event listener and start the load.
	// Listen for "DOMContentLoaded" instead of "load" because background loads
	// don't fire "load" events.
	iframe.addEventListener("DOMContentLoaded", handleParse, false);
	var uriLoader = Cc["@mozilla.org/uriloader;1"].getService(Ci.nsIURILoader);
	uriLoader.openURI(channel, true, iframe.docShell);
};

var gPerformancingUtil = null;

function loadPerFormancingUtil(noInit) {
	if (gPerformancingUtil == null){
		try {
			gPerformancingUtil = new performancingUtil();
		} catch(e) {
		}
		
		if(!noInit) {
			gPerformancingUtil.init();
		}
	}
}
